package com.zhouyu.exampleSpSource.controller.common;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.Set;

/**
 * Description:
 *
 * @author: zhou yu
 * @create: 2022-10-15 12:22
 */
@Service
public class RedisController {

    @Autowired
    RedisTemplate redisTemplate;

    @Scheduled(cron = "0 0/1 * * * ?")
    public void redisZset(){
        try {
            System.out.println("开始");
            String wx = String.format("SYT:PAY_OP:TRADE:%s", "WX");
            String date = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm") + ":00";
            Date scoreDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date);
            Long seconds = scoreDate.getTime()/1000;
            redisTemplate.opsForZSet().add(wx,Math.random(),new Double(seconds));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        zsetGet();
    }

    public  void zsetGet(){
        String  wx= String.format("SYT:PAY_OP:TRADE:%s", "WX");
        Long start = LocalDateTime.now().minusMinutes(1).toEpochSecond(ZoneOffset.of("+8"));
        Long end = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
        redisTemplate.opsForZSet().removeRangeByScore(wx,start,-1);
        Set<ZSetOperations.TypedTuple<Object>> set = redisTemplate.opsForZSet().rangeByScoreWithScores(wx, start, end);
        for (ZSetOperations.TypedTuple<Object> typedTuple : set) {
            Double score = typedTuple.getScore();
            Double value = typedTuple.getScore();
            System.out.println(score.longValue()+":"+value);
        }
    }
}
